from base64 import b64decode
from io import StringIO
from random import sample

from Tools.i18n.msgfmt import generate
from django.shortcuts import render, redirect
from django.http import HttpResponse, HttpRequest, JsonResponse
# Create your views here.
# from django_redis.serializers import json
# import json
from polls.captcha import Captcha
from polls.random import to_md5_hex, random_text, check_username

'''
Django ORM框架  - 解决对象模型到关系模型双向转换问题
                -性能下降
'''
from polls.models import Subject, User
from polls.models import Teacher


def index(request):
    '''首页（获取所有学科）'''
    queryset = Subject.objects.all()

    context = {
        'subjects': queryset

    }
    return render(request, 'subjects.html', context)


def show_teacher(request):
    '''显示指定学科的老师'''
    try:
        sno = request.GET['sno']
        subject = Subject.objects.get(no=sno)
        queryset = Teacher.objects.filter(subject__no=sno)
        context = {
            'subject': subject,
            'teachers': queryset
        }
        return render(request, 'teachers.html', context)
    except(KeyError, ValueError, Subject.DoesNotExist):
        return redirect('/')


# def praise(request):
#
#     tno =request.GET.get('tno', '0')
#     sno = request.GET.get('sno', '0')
#     # filter返回一个集合.first（），不存在拿不到值，但需要一个判断
#     try:
#         teacher = Teacher.objects.get(no=tno)
#         teacher.good_count += 1
#         teacher.save()
#     except (ValueError,Teacher.DoesNotExist):
#         pass
#     return redirect(f'/teachers/?sno={sno}')
#
#
# def badComent(request):
#         try:
#             tno =request.GET.get('tno', '0')
#             sno = request.GET.get('sno', '0')
#             teacher = Teacher.objects.get(no=tno)
#             teacher.bad_count += 1
#             teacher.save()
#         except (ValueError,Teacher.DoesNotExist):
#             pass
#         return redirect(f'/teachers/?sno={sno}')


def comment(request):
    ''''好评或差评'''

    if request.session.get('userid') is None:
        data = {'code': 10002, 'message': '请先登录'}
    else:
        tno = request.GET.get('tno', '0')
        # sno = request.GET.get('sno', '0')
        try:
            teacher = Teacher.objects.get(no=tno)
            if request.path.startswith('/good'):
                # request.method 获取请求方式
                # request.path 获取请求路径
                teacher.good_count += 1
            else:
                teacher.bad_count += 1
            teacher.save()
            data = {'code': 10000, 'message': '操作成功'}
        except (ValueError, Teacher.DoesNotExist):
            data = {'code': 10001, 'message': '操作失败'}
    return JsonResponse(data)


def login(request):
    '''登录'''
    backurl = request.GET.get('backurl', '')

    hint = ''
    if request.method == 'POST':
        code_from_user = request.POST.get('captcha', '0').lower()
        code_from_serv = request.session.get('code', '1').lower()
        if code_from_serv == code_from_user:
            '''获取用户输入的值'''
            username = request.POST.get('username', '')
            password = request.POST.get('password', '')
            print(username, password)
            '''如果有值输入'''
            if username and password:
                '''获取数据库中用户数据'''
                usernames = User.objects.filter(username=username).first()
                print('===', usernames.password)
                '''判断用户是否存在'''
                '''将用户输入密码转哈希值比较'''
                pd = to_md5_hex(password)
                if usernames.password == pd:

                    # 登录成功后为了记住这个登录成功的用户
                    # 可以在服务器端保存和用户相关的信息
                    # 可以将这些信息保存在Django框架提供的session对象中
                    request.session['username'] = usernames.username
                    request.session['userid'] = usernames.no
                    if backurl:
                        backurl = b64decode(backurl).decode()
                    else:
                        backurl = '/'
                    return redirect(backurl)
                else:
                    hint = '用户名或者密码错误'
            else:
                hint = '没有该用户'

        else:
            hint = '请输入正取的验证码'
    context = {
        'hint': hint,
        'backurl': backurl
    }
    return render(request, 'login.html', context)


def logout(request):
    '''注销（退出登录）'''
    request.session.flush()
    return redirect('/')


def get_captcha(request):
    '''获取验证码图片'''
    code = random_text()
    image_data = Captcha.instance().generate(code)
    request.session['code'] = code
    return HttpResponse(image_data, content_type='image/png')

#
# def index(request: HttpRequest):
#     fruits = ['今天不吃', '苹果', '香蕉', '菠萝', '草莓', '猕猴桃', '西瓜', '火龙果']
#     greet = ['大哥你看', '大佬你看', '帅哥你看']
#     context = {
#         'fruits': sample(fruits, 3),
#         'greeting': sample(greet, 1)
#     }
#     return render(request, 'subjects.html',context)
# def index(request: HttpRequest):
#
#     fruits = ['今天不吃','苹果','香蕉','菠萝','草莓','猕猴桃','西瓜','火龙果']
#     content = StringIO()
#     content.write('<h2>今日推荐</h2>')
#     content.write('<hr>')
#     content.write('<ul>')
#     for fruits in sample(fruits,3):
#         content.write(f'\t<li>{fruits}</li>')
#
#     content.write('</ul>')
#     return HttpResponse(content.getvalue())
